﻿using System;
using System.Collections;
using System.Runtime.Remoting;
using System.Collections.Generic;

namespace HZ.Common
{
    public class RemotingHelper
    {
        private static bool _isInit;
        private static IDictionary _wellKnownTypes;

        public static Object GetObject(Type type)
        {
            if (!_isInit) InitTypeCache();
            WellKnownClientTypeEntry entr =
                 (WellKnownClientTypeEntry)_wellKnownTypes[type];
            if (entr == null)
            {
                throw new RemotingException("Type not found!");
            }
            return Activator.GetObject(entr.ObjectType, entr.ObjectUrl);
        }

        /// <summary>
        /// 初始化缓存
        /// </summary>
        private static void InitTypeCache()
        {
            _isInit = true;
            _wellKnownTypes = new Hashtable();
            foreach (WellKnownClientTypeEntry entr in
                      RemotingConfiguration.GetRegisteredWellKnownClientTypes())
            {
                if (entr.ObjectType == null)
                {
                    throw new RemotingException("A configured type could not " +
                             "be found. Please check spelling");
                }
                _wellKnownTypes.Add(entr.ObjectType, entr);
            }
        }

        #region 泛型的解析方法
        /// <summary>
        /// 泛型解析Remoting接口
        /// </summary>
        /// <typeparam name="T">传入的接口名</typeparam>
        /// <returns>远程接口对象</returns>
        public static T GetObject<T>()
        {
            if (!_isInit)
                InitTypeCache();

            WellKnownClientTypeEntry entry = (WellKnownClientTypeEntry)_wellKnownTypes[typeof(T)];

            if (entry == null)
            {
                throw new RemotingException("Type not found!");
            }

            return (T)Activator.GetObject(entry.ObjectType, entry.ObjectUrl);
        }

        #endregion

    }
}
